<!--
 * @author dumeng
 大屏数据配置
 -->
<template>
  <div class="screen-config">
    <el-collapse-transition>
      <div v-show="searchshow" class="course-search merge">
        <span class="svg-container">
          <svg-icon icon-class="search" />
        </span>
        <el-input
          v-model.trim="searchQuery.configRemark"
          placeholder="请输入配置名称搜索"
          class="search-input"
          @keyup.enter.native="handleFilter"
        />
        <div class="course-search-btn">
          <el-button class="filter-item" type="primary" @click="handleFilter">搜索</el-button>
          <el-button class="filter-item" type="primary" @click="resettingBtn">重置</el-button>
          <span class="course-search-more" @click="searchshow = !searchshow">
            更多筛选条件
            <i class="el-icon-arrow-down" />
          </span>
        </div>
      </div>
    </el-collapse-transition>
    <el-collapse-transition>
      <div v-show="!searchshow" class="course-search separate">
        <div class="course-search-inner">
          <el-row>
            <el-col :span="12">
              <div class="search-inner-item">
                <div class="item-label">配置名称</div>
                <el-input
                  v-model.trim="searchQuery.configRemark"
                  class="filter-item"
                  placeholder="请输入配置名称搜索"
                />
              </div>
            </el-col>
            <el-col :span="12">
              <div class="search-inner-item">
                <div class="item-label">状态</div>
                <el-checkbox-group v-model="choose" style="margin-top:15px;">
                  <el-checkbox label="ZT01">启用</el-checkbox>
                  <el-checkbox label="ZT02">禁用</el-checkbox>
                </el-checkbox-group>
              </div>
            </el-col>
          </el-row>
        </div>
        <div class="course-search-btn">
          <el-button type="primary" @click="handleFilter">搜索</el-button>
          <el-button class="filter-item" type="primary" @click="resettingBtn">重置</el-button>
          <span class="course-search-more" @click="searchshow = !searchshow">
            精简筛选条件
            <i class="el-icon-arrow-up" />
          </span>
        </div>
      </div>
    </el-collapse-transition>
    <div class="btn-container">
      <div class="btn-container-title">
        <span>大屏数据管理</span>
      </div>
      <div class="btn-container-btns">
        <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate">新建</el-button>
      </div>
    </div>
    <div class="table">
      <v-table
        :list="list"
        tag="screenConfigList"
        :list-loading="listLoading"
        :filter-column="filtercolumn"
      >
        <el-table-column label="操作" fixed="right" align="center" min-width="100" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button type="text" size="mini" @click="handlePublish(scope.row)">{{ scope.row.configStatus === "ZT01" ? "禁用" : "启用" }}
            </el-button>
            <el-button type="text" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
            <el-button type="text" size="mini" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </v-table>
    </div>
    <div class="btn-pagion fix">
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="pageQuery.page"
        :limit.sync="pageQuery.pageSize"
        @pagination="getList"
      />
    </div>
    <!--编辑配置    -->
    <el-dialog
      v-el-drag-dialog
      :close-on-click-modal="false"
      :title="textMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      center
      width="800px"
    >
      <el-form
        ref="addForm"
        v-loading="submitloading"
        :model="addForm"
        :rules="addRules"
        class="dataForm"
        label-position="right"
        label-width="120px"
      >
        <el-form-item label="配置名称" prop="configRemark">
          <el-input v-model.trim="addForm.configRemark" placeholder="请输入配置名称" />
        </el-form-item>
        <el-form-item label="配置code" prop="configName">
          <el-input v-model.trim="addForm.configName" placeholder="请输入配置code" />
        </el-form-item>
        <el-form-item label="配置值" prop="configValue">
          <json-editor
            v-model="addForm.configValue"
            :show-btns="false"
            :mode="'code'"
            lang="zh"
            @has-error="(err) =>{jsonHasErr = err}"
          />
        </el-form-item>
        <el-form-item label="排序" prop="configSort">
          <el-input v-model.trim="addForm.configSort" placeholder="请输入排序值" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button style="padding: 10px 30px;" @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import VTable from '@/components/Table'
import {
  mapGetters
} from 'vuex'
import {
  queryPage,
  add,
  get,
  update,
  deleteById,
  updateStatus
} from '../api'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import permission from '@/directive/permission/index.js' // 权限判断指令
// eslint-disable-next-line no-unused-vars
import elDragDialog from '@/directive/el-drag-dialog'
import JsonEditor from '@/components/JsonEditor'
export default {
  name: 'ScreenConfig',
  components: {
    Pagination,
    VTable,
    JsonEditor
  },
  directives: {
    permission,
    elDragDialog
  },
  data() {
    return {
      submitloading: false,
      pageQuery: {
        page: 1,
        pageSize: 10
      },
      addForm: {
        id: '',
        configRemark: '',
        configName: '',
        configValue: '',
        configSort: ''
      },
      searchshow: true,
      searchQuery: {
        configRemark: '',
        configStatus: []
      },
      list: [],
      total: 0,
      dialogStatus: '',
      dialogFormVisible: false,
      textMap: {
        create: '新建',
        update: '编辑'
      },
      choose: [],
      listLoading: false,
      addRules: {
        configRemark: [{
          required: true,
          message: '请填配置名称',
          trigger: 'blur'
        }],
        configName: [{
          required: true,
          message: '请填写配置code',
          trigger: 'blur'
        }],
        configValue: [{
          required: true,
          message: '请填写配置值',
          trigger: 'change'
        }]
      },
      jsonHasErr: false
    }
  },
  computed: {
    ...mapGetters(['user'])
  },
  created() {
    this.getList()
  },
  methods: {
    /**
     * 启用/禁用
     */
    handlePublish(row) {
      this.$confirm(row.configStatus === 'ZT01' ? '确认禁用？' : '确认启用？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const configObj = {
          configStatus: row.configStatus === 'ZT01' ? 'ZT02' : 'ZT01',
          id: row.id
        }
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        updateStatus(configObj).then(res => {
          loading.close()
          if (res.data.code === '200') {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
            this.getList()
          }
        })
      }).catch(() => {
        loading.close()
      })
    },
    filtercolumn(scope, item) {
      return scope.row[item]
    },

    getList() {
      if (this.choose.length > 0) {
        this.searchQuery.configStatus = this.choose.join(',')
      } else {
        this.searchQuery.configStatus = ''
      }
      Object.assign(this.searchQuery, this.pageQuery)
      this.listLoading = true
      return new Promise((resolve, reject) => {
        queryPage(this.searchQuery).then(res => {
          this.listLoading = false
          this.list = res.data.data.rows || []
          this.total = res.data.data.total
        }).catch(error => {
          reject(error)
          this.listLoading = false
        })
      })
    },

    handleFilter() {
      this.pageQuery.page = 1
      this.getList()
    },
    resettingBtn() {
      this.pageQuery.page = 1
      this.pageQuery.pageSize = 10
      for (const key in this.searchQuery) {
        this.searchQuery[key] = ''
      }
      this.choose = []
      this.getList()
    },
    /**
     * 返回
     */
    handleCancel() {
      this.$router.back()
    },
    handleCreate() {
      this.dialogStatus = 'create'
      for (const key in this.addForm) {
        this.addForm[key] = ''
      }
      this.addForm.configStatus = 'ZT01'
      this.dialogFormVisible = true
    },
    handleUpdate(row) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get({
          id: row.id
        }).then(res => {
          loading.close()
          const data = res.data.data
          for (const key in this.addForm) {
            this.addForm[key] = key === 'configValue' ? JSON.parse(data[key]) : data[key]
          }
          this.addForm.id = data.id
          this.dialogStatus = 'update'
          this.dialogFormVisible = true
          this.$nextTick(() => {
            this.$refs['addForm'].clearValidate()
          })
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    handleDelete(row) {
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteById({
          ids: row.id
        }).then(res => {
          this.$message.success('删除成功!')
          this.getList()
        })
      }).catch(() => {
      })
    },
    createData() {
      if (this.jsonHasErr) {
        this.$message.error('配置值格式错误，请检查！')
        return
      }
      this.$refs['addForm'].validate(valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          const params = Object.assign({}, this.addForm)
          params.configValue = JSON.stringify(params.configValue)
          add(params).then(res => {
            loading.close()
            this.$message.success('创建成功！')
            this.dialogFormVisible = false
            this.pageQuery.size = 1
            this.getList()
            // eslint-disable-next-line handle-callback-err
          }).catch(err => {
            loading.close()
          })
        }
      })
    },
    updateData() {
      if (this.jsonHasErr) {
        this.$message.error('配置值格式错误，请检查！')
        return
      }
      this.$refs['addForm'].validate(valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '请稍后',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.3)'
          })
          const params = Object.assign({}, this.addForm)
          params.configValue = JSON.stringify(params.configValue)
          update(params).then(res => {
            loading.close()
            this.$message.success('编辑成功！')
            this.dialogFormVisible = false
            this.pageQuery.size = 1
            this.getList()
          })
          // eslint-disable-next-line handle-callback-err
            .catch(err => {
              loading.close()
            })
        }
      })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="scss" type="text/scss">
$dark_gray: #bfced6;
.screen-config {
  padding: 10px 20px 10px 10px;
  .course-search {
    background-color: #fff;
    padding: 0 10px;

    .svg-container {
      padding: 0 5px 0 10px;
      color: $dark_gray;
      vertical-align: middle;
      display: inline-block;

      &_login {
        font-size: 20px;
      }
    }

    .search-input {
      width: 60%;
      position: relative;

      &:after {
        content: "";
        position: absolute;
        left: -25px;
        right: 0;
        bottom: 8px;
        height: 1px;
        background: rgba(226, 227, 232, 1);
      }

      input {
        outline: none;
        background: transparent;
        border: none;
        outline: medium;
        padding: 0;

        &:focus {
          outline: none;
          background-color: transparent;
        }
      }
    }

    .course-search-btn {
      display: inline-block;
      float: right;

      .el-button.is-round {
        padding: 10px 30px;
        margin-right: 34px;
      }

      .course-search-more {
        font-size: 14px;
        font-weight: 500;
        @include font-color($mainColor);
        cursor: pointer;
        margin-left: 10px;
      }
    }

    &.merge {
      height: 50px;
      line-height: 50px;
    }

    &.separate {
      .course-search-inner {
        padding-top: 10px;

        .search-inner-item {
          .item-label {
            height: 30px;
            line-height: 30px;
            font-size: 14px;
            color: #a6a6a6;
            font-weight: 400;
          }

          .el-input {
            position: relative;

            .el-input__inner {
              border: none;
              padding: 0;
            }

            &:after {
              content: "";
              height: 1px;
              background-color: #e2e3e8;
              position: absolute;
              left: 0;
              right: 0;
              bottom: 0;
            }
          }
        }
      }

      .course-search-btn {
        text-align: center;
        display: block;
        float: none;
        height: 56px;
        line-height: 56px;
      }
    }
  }

  .btn-container {
    display: flex;
    align-items: center;
    margin-top: 5px;
    margin-bottom: 5px;

    .btn-container-title {
      flex: 1;
      height: 36px;
      line-height: 36px;
      font-size: 16px;
      color: rgba(51, 51, 51, 1);
    }
  }

  .dataForm {
    width: 100%;

    .el-radio__label {
      display: inline-block;
      max-width: 380px;
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
    }
  }

  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }

  .el-checkbox__label {
    font-weight: 400;
  }

  .el-form-item__label {
    // width: 90px !important;
  }

  .el-form-item__content {
    // margin-left: 90px !important;
  }
}
</style>
